package com.baymax.exception.handler;

import com.baymax.common.R;
import com.baymax.exception.GlobalException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * 全局异常捕获
 *
 * @Author: baymax
 * @CreateTime: 2023/3/30 16:34
 * @Version: 1.0
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 处理系统级别异常
     */
    @ExceptionHandler(Throwable.class)
    public Object handleException(Throwable e){
        return R.fail(e.getMessage());
    }

    /**
     * 自定义异常处理
     */
    @ExceptionHandler(value = GlobalException.class)
    @ResponseBody
    public Object myExceptionHandler(GlobalException e) {
        // 返回异常信息
        return R.fail(e.getMessage());
    }

    /**
     * 服务器异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public R<String> exception(Exception e) {
        log.error("服务器异常！ msg: -> ", e);
        return R.fail(e.getMessage());
    }

    /**
     * 无接口权限
     */
    @ExceptionHandler(AccessDeniedException.class)
    @ResponseBody
    public R<String> exception(AccessDeniedException e) {
        log.error("服务器异常！ msg: -> ", e);
        return R.fail(null, HttpStatus.FORBIDDEN.value(), e.getMessage());
    }

}

